package com.bodu.config;

import com.bodu.enums.GenTemplateEnum;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author:Administrator
 * @create:2022-04-21 10:30
 */
@Configuration
public class FreemarkerConfiguration {

    /**
     * 模板配置
     *
     * @return freemarker.template.Configuration 返回模板信息
     */
    private freemarker.template.Configuration configuration() throws Exception {
        freemarker.template.Configuration cfg = null;
        // Create your Configuration instance, and specify if up to what FreeMarker
        // version (here 2.3.27) do you want to apply the fixes that are not 100%
        // backward-compatible. See the Configuration JavaDoc for details.
        cfg = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_28);
        // Specify the source where the template files come from. Here I set a
        // plain directory for it, but non-file-system sources are possible too:
        // 模板文件的位置
//        cfg.setDirectoryForTemplateLoading(new File(templatesPath));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        // Don't log exceptions inside FreeMarker that it will thrown at you anyway:
        cfg.setLogTemplateExceptions(false);
        // Wrap unchecked exceptions thrown during template processing into TemplateException-s.
        cfg.setWrapUncheckedExceptions(true);

        return cfg;
    }

    @Bean
    public Template controllerTemplate() throws Exception {
        return getTemplate(GenTemplateEnum.CONTROLLER);
    }

    @Bean
    public Template serviceTemplate() throws Exception {
        return getTemplate(GenTemplateEnum.SERVICE);
    }

    @Bean
    public Template serviceImplTemplate() throws Exception {
        return getTemplate(GenTemplateEnum.SERVICE_IMPL);
    }

    @Bean
    public Template daoTemplate() throws Exception {
        return getTemplate(GenTemplateEnum.DAO);
    }

    @Bean
    public Template daoXmlTemplate() throws Exception {
        return getTemplate(GenTemplateEnum.DAO_XML);
    }

    /**
     * 得到模板
     *
     * @param genTemplateEnum 模板枚举
     * @return freemarker.template.Template
     */
    private Template getTemplate(GenTemplateEnum genTemplateEnum) throws Exception {
        InputStream inputStream = FreemarkerConfiguration.class.getResourceAsStream(genTemplateEnum.getTemplate());
        return new Template(genTemplateEnum.getKey(), new InputStreamReader(inputStream), configuration());
    }
}
